package models

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 脚本
type JobScript struct {
	Model        // 不用每次写ID 和 createAt了
	Name  string `json:"name" validate:"required,min=1,max=50" gorm:"uniqueIndex;type:varchar(100);comment:任务脚本名称，支持使用通配符*进行模糊搜索" `
	Lang  string `json:"lang"`
	//Creator User   `json:"Creator" `
	UserID uint
	//FlowNodes     []FlowNode `json:"flowNodes" gorm:"foreignKey:JobScriptRefer"`
	// 一对多关系 https://gorm.io/zh_CN/docs/has_many.html
	Code string `json:"code" gorm:"type:text;comment:脚本原始内容"`

	Key            string `json:"key" gorm:"-"` //给前端表格
	CreateUserName string `json:"createUserName" gorm:"-"`
}

func (obj *JobScript) Create() error {
	return Db.Create(obj).Error

}
func (obj *JobScript) DeleteOne() error {

	return Db.Select(clause.Associations).Unscoped().Delete(obj).Error

}

func (obj *JobScript) CreateOne() error {
	return Db.Create(obj).Error

}

func (obj *JobScript) UpdateOne() error {
	return Db.Where("id = ?", obj.ID).Updates(obj).Error

}

func (obj *JobScript) UpdateFlowNodes(nodes []FlowNode) error {

	return Db.Model(obj).Association("FlowNodes").Replace(nodes)

}

func (obj *JobScript) FillFrontAllData() {
	dbUser, _ := GetUserById(int(obj.UserID))
	if dbUser != nil {
		obj.CreateUserName = dbUser.Username
	}

	obj.Key = fmt.Sprintf("%d", obj.ID)

}
func GetJobScriptAll() (objs []*JobScript, err error) {
	err = Db.Find(&objs).Error
	return
}

func GetJobScriptCount() int {
	var count int64
	Db.Table("form_designs").Count(&count)
	return int(count)
}

// select * from ecs where
func GetJobScriptByIdsWithLimitOffset(ids []int, limit, offset int) (objs []*JobScript, err error) {
	err = Db.Limit(limit).Offset(offset).Find(&objs, ids).Error
	return
}

func GetJobScriptByInstanceId(instanceId string) (*JobScript, error) {

	var dbObj JobScript
	err := Db.Where("instance_id = ?", instanceId).Preload("FlowNodes").First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("JobScript不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetJobScriptById(id int) (*JobScript, error) {

	var dbObj JobScript
	err := Db.Where("id = ?", id).First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("JobScript不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}
